package com.example.demo1.controller;

import com.example.demo1.pojo.dto.userCreateDto;
import com.example.demo1.pojo.dto.userUpdateDto;
import com.example.demo1.pojo.result.result;
import com.example.demo1.pojo.user;
import com.example.demo1.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/users")
@Validated
@CrossOrigin(origins = "*")
public class userController {
    @Autowired
    private userService service;

    @PostMapping
    public result<user> createUser(@Validated @RequestBody userCreateDto userDto) {
        try{
            user user=userService.createUser(userDto);
            return result.success("user create success",user);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public result<user> getUser(@PathVariable Integer id) {
        try{
            Optional<user> userOpt=userService.getUserById(id);
            if(userOpt.isPresent()){
                return result.success(userOpt.get());
            }else{
                return result.error("user not found");
            }
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public result<user> updateUser(
            @PathVariable Integer id,
            @Validated @RequestBody userUpdateDto userDto){
        try{
            user user=userService.updateUser(id,userDto);
            return result.success("user update success",user);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public result<user> deleteUser(@PathVariable Integer id) {
        try{
            userService.deleteUser(id);
            return  result.success("user delete success",null);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @GetMapping
    public result<List<user>> getAllUsers() {
        try{
            List<user> users=userService.getAllUsers();
            return result.success(users);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }
}
